import { useMemo, useState } from 'react';
import type { ErrorMsg, PreviewCube } from 'umi';
import { isNull, isNumber } from 'lodash';
import { Button, Space } from 'antd';
import type { DragStartParams, DropResult } from 'react-smooth-dnd';
import { Container, Draggable } from 'react-smooth-dnd';
import {
  ArrowDownOutlined,
  ArrowUpOutlined,
  CopyOutlined,
  DeleteOutlined,
} from '@ant-design/icons';

import useDispatcher from '../hooks/useDispatcher';

interface IPreviewProps {
  itemList: PreviewCube[];
  activeId: string;
  errorMap: ErrorMsg;
  showPreViewItems: boolean;
  goodsList: any[];
}

import style from './index.less';

const Preview: React.FC<IPreviewProps> = (props) => {
  const [isSource, setIsSource] = useState(false);
  const dispatch = useDispatcher();

  const addCubeHandle = (type: string, addedIndex: number) => {
    dispatch('addCube', {
      type,
      addedIndex,
    });
  };

  const sortCubeHandle = (removedIndex: number, addedIndex: number) => {
    dispatch('sortPreview', {
      removedIndex,
      addedIndex,
    });
  };

  const sortCurrentCube = (id: string) => {
    dispatch('setActiveSortItemId', {
      id,
    });
  };

  const deleteCurrentCube = (index: number) => {
    dispatch('deleteCube', {
      index,
    });
  };

  const copyCurrentCube = (index: number) => {
    dispatch('copyCube', {
      index,
    });
  };

  const upCube = (i: number) => {
    if (!i) return;
    sortCubeHandle(i, i - 1);
  };

  const downCube = (i: number) => {
    if (i === props.itemList.length - 1) return;
    sortCubeHandle(i + 1, i);
  };

  const onDropStartHandle = (e: DragStartParams) => {
    setIsSource(e.isSource);
  };

  const onDropHandle = (e: DropResult) => {
    console.log(e, 222);
    setIsSource(false);
    const { addedIndex, removedIndex, payload } = e;
    // 新增
    if (payload && isNumber(addedIndex)) {
      addCubeHandle(payload.type, addedIndex);
      return;
    }

    if (isNumber(addedIndex) && isNumber(removedIndex)) {
      sortCubeHandle(removedIndex, addedIndex);
    }

    // 拖到预览区域外就删除
    if (isNull(addedIndex) && isNumber(removedIndex)) {
      dispatch('deleteCube', {
        index: removedIndex,
      });
    }
  };

  const onDragEnterHandle = () => {
    if (isSource) {
      const node = document.querySelector(`.${style['sort-drag']}`);
      node?.classList.remove(`${style.out}`);
    } else {
      const node = document.querySelector(`.${style['cube-item-placeholder']}`);
      const span = document.createElement('span');
      span.textContent = '将模块放于此处';
      node?.append(span);
    }
  };

  const onDragLeaveHandle = () => {
    if (isSource) {
      const node = document.querySelector(`.${style['sort-drag']}`);
      node?.classList.add(`${style.out}`);
    }
  };

  const showItems = useMemo<boolean>(
    () => (!props.activeId ? props.showPreViewItems : true),
    [props.showPreViewItems, props.activeId],
  );

  return (
    <div className={style.preview}>
      {/* @ts-ignore */}
      <Container
        groupName="cube"
        removeOnDropOut
        style={{ minHeight: 'calc(667px + var(--innerHeight))' }}
        dragClass={style['sort-drag']}
        dropPlaceholder={
          !isSource
            ? {
                className: style['cube-item-placeholder'],
              }
            : {
                className: style['sort-item-placeholder'],
              }
        }
        onDragEnter={onDragEnterHandle}
        onDragLeave={onDragLeaveHandle}
        onDragStart={onDropStartHandle}
        onDrop={onDropHandle}
      >
        {showItems &&
          props.itemList.map((item, i) => {
            const { view: View, initialValues, type } = item;
            const goodsList = type === 'Goods' ? { goodsList: props.goodsList } : {};
            return (
              // @ts-ignore
              <Draggable
                id={item.id}
                key={item.id}
                onClick={() => sortCurrentCube(item.id)}
                className={`${style['preview-item']} ${
                  props.activeId === item.id ? style.active : ''
                } ${!!props.errorMap[item.id] ? style.error : ''}`}
              >
                <View data={initialValues as any} {...goodsList} />
                {props.activeId === item.id && (
                  <Space direction="vertical" className={style['preview-tool']}>
                    <Space.Compact direction="vertical">
                      <Button icon={<ArrowUpOutlined />} onClick={() => upCube(i)} />
                      <Button icon={<ArrowDownOutlined />} onClick={() => downCube(i)} />
                    </Space.Compact>
                    <Space.Compact direction="vertical">
                      <Button icon={<DeleteOutlined />} onClick={() => deleteCurrentCube(i)} />
                      <Button icon={<CopyOutlined />} onClick={() => copyCurrentCube(i)} />
                    </Space.Compact>
                  </Space>
                )}
                <div className={style['cube-name']}>{item.title}</div>
              </Draggable>
            );
          })}
      </Container>
    </div>
  );
};

export default Preview;
